package cn.sciento.farm.devicemanager.gateway.uplink.service.insectSituationLamp.impl;

import cn.sciento.farm.devicemanager.common.constant.DeviceImgConstant;
import cn.sciento.farm.devicemanager.common.constant.RedisConstant;
import cn.sciento.farm.devicemanager.common.util.BaseContextHandler;
import cn.sciento.farm.devicemanager.common.util.RedisUtil;
import cn.sciento.farm.devicemanager.common.util.qiniu.*;
import cn.sciento.farm.devicemanager.dao.entity.*;
import cn.sciento.farm.devicemanager.gateway.model.uplink.InsectLampParam;
import cn.sciento.farm.devicemanager.gateway.model.uplink.InsectLampSwitch;
import cn.sciento.farm.devicemanager.gateway.uplink.service.insectSituationLamp.InsectSituationLampDisposeService;
import cn.sciento.farm.devicemanager.service.*;
import cn.sciento.fluorite.api.device.manage.CapturePicApi;
import cn.sciento.fluorite.api.token.GetToken;
import cn.sciento.fluorite.constants.StatusConstant;
import cn.sciento.fluorite.response.AccessToken;
import cn.sciento.fluorite.response.BasicResponse;
import cn.sciento.fluorite.response.CapturePicture;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author Walton
 * @since 2020/8/25 14:51
 */
@Slf4j
@Order(1)
@Service(value = "InsectSitautionLampDataDisposeService")
public class InsectSituationLampDataDisposeService implements InsectSituationLampDisposeService {

    @Value("${fluorite.appKey}")
    private String defaultAppKey;

    @Value("${fluorite.appSecret}")
    private String defaultAppSecret;

    @Autowired
    private TenantConfigService tenantConfigService;

    @Autowired
    private DevInsectSituationLampService insectSituationLampService;

    @Autowired
    private DevInsectImageService imageService;

    @Autowired
    private DevInsectSituationLampHistoryService insectLampHistoryService;

    @Autowired
    private DevInsectSituationLampLogService insectSituationLampLogService;

    @Override
    public void changeSwitch(InsectLampSwitch insectLampSw){
        List<DevInsectSituationLamp> insectLampList = insectSituationLampService.getByEuiAndModbusAddr(insectLampSw.getEui(),insectLampSw.getModbusAddr());
        if (insectLampList == null) {
            return;
        }
        DevInsectSituationLamp insectLamp = insectLampList.get(0);
        insectLamp.setModbusAddr(insectLampSw.getModbusAddr());
        insectLamp.setTimeSwitch(insectLampSw.getTimeSwitch());
        insectLamp.setHeatSwitch(insectLampSw.getHeatSwitch());
        insectLamp.setTileSwitch(insectLampSw.getTileSwitch());
        insectLamp.setLightSwitch(insectLampSw.getLightSwitch());
        insectLamp.setSweepSwitch(insectLampSw.getSweepSwitch());
        insectLamp.setPhtotsSwitch(insectLampSw.getPhtotsSwitch());
        insectLamp.setUpDoorSwitch(insectLampSw.getUpDoorSwitch());
        insectLamp.setLowDoorSwitch(insectLampSw.getLowDoorSwitch());
        insectLamp.setLighthouseSwitch(insectLampSw.getLighthouseSwitch());
        insectSituationLampService.update(insectLamp);
        // 1.检查摄像头是否在线
        if(insectLampSw.getPhtotsSwitch() == 1){
            // 2.判断摄像头是否在线,如果在线,添加延时执行任务
            delayTask(insectLamp);
        }
    }

    private void delayTask(DevInsectSituationLamp insectLamp){
        ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                capturePic(insectLamp);
            }
        };
        executor.schedule(runnable,insectLamp.getDelay(),TimeUnit.SECONDS);
        executor.shutdown();
    }

    private void capturePic(DevInsectSituationLamp insectLamp){
        CapturePicApi capturePicApi = new CapturePicApi(refreshToken(), insectLamp.getPhtotsSerial());
        BasicResponse<CapturePicture> basicResponse = capturePicApi.executeApi();
        CapturePicture capturePicture = basicResponse.getData();
        // 2.1.不在线,添加日志
        if (capturePicture.getPicUrl() == null) {
            DevInsectSituationLampLog insectLog = new DevInsectSituationLampLog();
            insectLog.setInsectId(insectLamp.getId());
            insectLog.setPhtotsSerial(insectLamp.getPhtotsSerial());
            insectLog.setTenantId(insectLamp.getTenantId());
            insectLog.setCreateTime(System.currentTimeMillis());
            insectLog.setContent("图片未截取成功");
            insectSituationLampLogService.insert(insectLog);
            return;
        }
        String key = String.format(DeviceImgConstant.SIMPLE_TEMPLATE, DeviceImgConstant.TYPE_CAMERA,
                UUID.randomUUID().toString().replace("-", "") + ".jpg");
        QiniuBucketUtil.fetch(capturePicture.getPicUrl(), key);
        String url = null;
        try {
            url = QiniuClientUtil.getUrl(key);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        DevInsectImage devInsectImage = new DevInsectImage();
        devInsectImage.setImageUrl(url);
        devInsectImage.setInsectId(insectLamp.getId());
        devInsectImage.setTenantId(insectLamp.getTenantId());
        devInsectImage.setCreateTime(System.currentTimeMillis());
        imageService.insert(devInsectImage);
    }
    @Override
    public void changeParam(InsectLampParam insectLampParam) {
        List<DevInsectSituationLamp> insectLampList = insectSituationLampService.getByEuiAndModbusAddr(insectLampParam.getEui(),insectLampParam.getModbusAddr());
        if (insectLampList == null) {
            return;
        }
        DevInsectSituationLamp insectLamp = insectLampList.get(0);

        insectLamp.setModbusAddr(insectLampParam.getModbusAddr());
        insectLamp.setLinghtControlTime(insectLampParam.getLinghtControlTime());
        insectLamp.setStartControlTime(insectLampParam.getStartControlTime());
        insectLamp.setEndControlTime(insectLampParam.getEndControlTime());
        insectLamp.setCollectTime(insectLampParam.getCollectTime());
        insectLamp.setHeatTimeSet(insectLampParam.getHeatTimeSet());
        insectLamp.setHeatTemperatureSet(insectLampParam.getHeatTemperatureSet());
        insectLamp.setDataPeriod(insectLampParam.getDataPeriod());
        insectLamp.setPhtotsPeriod(insectLampParam.getPhtotsPeriod());
        insectLamp.setRatio(insectLampParam.getRatio());
        insectLamp.setVoltageBattery(insectLampParam.getVoltageBattery());
        insectLamp.setTemperatureControl(insectLampParam.getTemperatureControl());
        insectLamp.setRainControl(insectLampParam.getRainControl());
        insectLamp.setLighthouseControl(insectLampParam.getLighthouseControl());
        insectLamp.setHeatTemperatureActual(insectLampParam.getHeatTemperatureActual());
        insectLamp.setHeatTimeActual(insectLampParam.getHeatTimeActual());
        insectSituationLampService.update(insectLamp);
        addHistory(insectLampParam, insectLamp);
    }

    private void addHistory(InsectLampParam insectLampParam,DevInsectSituationLamp insectLamp){
        DevInsectSituationLampHistory insectLampHistory = new DevInsectSituationLampHistory();
        if (insectLampParam.getHeatTemperatureActual() != null && insectLampParam.getVoltageBattery() != null) {
            insectLampHistory.setModbusAddr(insectLampParam.getModbusAddr());
            insectLampHistory.setHeatTemperatureActual(insectLampParam.getHeatTemperatureActual());
            insectLampHistory.setVoltageBattery(insectLampParam.getVoltageBattery());
            insectLampHistory.setCreateTime(System.currentTimeMillis());
            insectLampHistory.setTenantId(insectLamp.getTenantId());
            insectLampHistoryService.insert(insectLampHistory);
        }
    }

    private String refreshToken() {
        String tenantId = BaseContextHandler.getTenantId();
        if(StringUtils.isEmpty(tenantId)){
            tenantId = "base";
        }
        String redisToken = (String) RedisUtil.getCacheSimple(RedisConstant.FLUORITE_ACCESS_TOKEN+tenantId);
        if (StringUtils.isEmpty(redisToken)) {
            String appKey = defaultAppKey;
            String appSecret = defaultAppSecret;
            // 是否启动自家的系统
            if(!tenantId.equals("base")){
                TenantConfig tenantConfig = tenantConfigService.get(tenantId);
                if(tenantConfig != null){
                    if(StringUtils.isNotEmpty(tenantConfig.getYsAppKey())
                            && StringUtils.isNotEmpty(tenantConfig.getYsSecret())){
                        appKey = tenantConfig.getYsAppKey();
                        appSecret = tenantConfig.getYsSecret();
                    }
                }
            }
            log.info(appKey + "---------" + appSecret);
            GetToken getToken = new GetToken(appKey, appSecret);
            BasicResponse<AccessToken> basicResponse = getToken.executeApi();
            if (basicResponse.getCode().equals(StatusConstant.OK)) {
                RedisUtil.putCacheStr(RedisConstant.FLUORITE_ACCESS_TOKEN+tenantId, basicResponse.getData().getAccessToken(), 3600L * 24 * 6);
                return basicResponse.getData().getAccessToken();
            } else {
                log.error("获取萤石云token失败。" + basicResponse);
                return "";
            }
        } else {
            return redisToken;
        }
    }

}
